import {reqHeader,proxy} from '../../utils/util.js';
import LoginStore from './store.js';
const bindPhoneObj = {
  key:'thirdBind',
  title: '绑定手机号',
  placeholder1: '请输入手机号码',
  placeholder2: '请输入验证码',
  bottomTip: '用户切换账号邮箱登录',
  btnText:'绑定'
}

const accountObj = {
  key:'account',
  title: '账号登录',
  placeholder1: '请输入账号/邮箱',
  placeholder2: '请输入密码',
  bottomTip: '用户切换手机验证码登录',
  btnText:'登录'
}
const app = getApp();

Page({
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    sendCodeMsg:'获取验证码',
    sendCodeNum:'',
    Timer:null,
    loading:false,
    errorTip:'',
    tipType: 'error',
    infoObj: {}

  },
  inputChange:function(key,value){
    value = value.replace(/(^\s*)|(\s*$)/g, "");
    let infoObj = this.data.infoObj;
    infoObj[key] = value ;
    this.setData({
      infoObj:infoObj
    })
  },
  inputPhone:function(e){
    this.inputChange("phoneNumber", e.detail.value);
  },
  inputPwd: function (e) {
    this.inputChange("code", e.detail.value);
  },
  inputCode: function (e) {
    this.inputChange("code", e.detail.value);
  },
  sendCode:function(e){
    let me = this;
    wx.request({
      url: `${proxy}/user/v2/sendPhoneCode`,
      method: 'POST',
      data:{
        phone: this.data.infoObj.phoneNumber,
        countryCode:'86'
      },
      header: {
        'content-type':'application/x-www-form-urlencoded',
        PF500MClient: 'wechatapplets'
      },
      success: function (data) {
        data = data.data;
        if (data.status == 200) {
          //发送验证码成功
          me.setData({
            sendCodeMsg: 's后重新发送',
            sendCodeNum: 60
          }, function () {
            me.data.Timer = setInterval(function () {
              let sendCodeNum = me.data.sendCodeNum - 1;
              if (sendCodeNum == 0) {
                clearInterval(me.data.Timer);
                me.setData({
                  sendCodeNum: '',
                  sendCodeMsg: '再次获取验证码'
                });
              } else {
                me.setData({
                  sendCodeNum: sendCodeNum
                });
              }
            }, 1000);
          });
        } else {
          // console.log(data.message);
          me.setData({
            errorTip: data.message
          })
        }
      }
    })
  },

  submitBindPhone:function(){
    let infoObj = this.data.infoObj;
    let urlStr,paramsData;
    if (infoObj.key === 'thirdBind'){
      if (!this.validatePhone()) {
        return;
      }
      let userInfo = LoginStore.wxUserInfo;
      urlStr = `${proxy}/user/v2/thirtPartloginWithBindMobile`;
      paramsData = {
        loginId: LoginStore.openId,
        loginType: 'weixin',
        nickName: userInfo.nickName,
        avatar: userInfo.avatarUrl,
        phone:infoObj.phoneNumber,
        code: infoObj.code,
        unionId: LoginStore.unionId,
        countryCode: '86'
      }
    }else{
      urlStr = `${proxy}/user/v2/tologin`;
      paramsData = {
        userName: infoObj.phoneNumber,
        password: infoObj.code,
        countryCode:'86'
      }
    }

    wx.showLoading({
      mask: true,
      title: 'loading...'
    });
    
    let me = this;
    wx.request({
      url: urlStr,
      method: 'POST',
      data: paramsData,
      header: Object.assign({
        'content-type': 'application/x-www-form-urlencoded'
      }, reqHeader),
      success: function (data) {
        data = data.data;
        wx.hideLoading();
        if (data.status == 200) {
          LoginStore.setUserInfo(data.userAccountInfo);
          if (infoObj.key === 'thirdBind'){
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];
            prevPage.setData({
              freshMark: true
            }, function () {
              wx.navigateBack({
                delta: 1
              })
            });
          }else{
            wx.reLaunch({
              url: '/pages/userInfo/userInfo?userId=' + LoginStore.userInfo.userId
            })
          }
          
        } else {
          me.setData({
            errorTip: data.message
          });
        }
      },
      fail:function(e){
        wx.hideLoading();
        me.setData({
          errorTip: e
        });
      }
    })
  },
  validatePhone:function(){
    let phone = this.data.infoObj.phoneNumber;
    let reg = /[0-9]{11}/;
    if (!phone.match(reg)) {
      this.setData({
        errorTip: '请输入正确的手机号！'
      });
      return false;
    }else{
      return true;
    }

  },
  obtainCode:function(){
    if (!this.validatePhone()){
      return;
    }

    this.sendCode();
  },

  redirection:function(){
    let params = this.data.pageInfo;
    let urlStr = '';
    if (params.page === 'detail') {
      urlStr = '/pages/detail/detail?photoId=' + params.options.photoId + '&contestId=' + params.options.contestId;
    } else if (params.page === 'userInfo') {
      urlStr = '/pages/userInfo/userInfo?userId=' + params.options.userId;
    } else if (params.page === 'contest'){
      urlStr = '/pages/contest/contest?id=' + params.options.id;
    }else{
      urlStr = '/pages/contestList/contestList';
    }
    wx.redirectTo({
      url: urlStr
    });
  },
  closeMsg:function(){
    this.setData({
      errorTip: ''
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let pageInfo = {};
    if (options.pageInfo){
      pageInfo = JSON.parse(options.pageInfo);
    }

    let infoObj = bindPhoneObj;
    if (options.loginType === 'account'){
      infoObj = accountObj
    }
    infoObj = {
      ...infoObj, 
      phoneNumber: '',
      code: ''
    }
    
    this.setData({
      pageInfo: pageInfo,
      infoObj: infoObj
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   
  onShareAppMessage: function () {
  
  }
  */
})